package com.lzyjkz.quick_components.Interceptor;

import com.lzyjkz.quick_components.annotation.ExecutedMethodLog;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class ExecutedTimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            ExecutedMethodLog methodAnnotation = handlerMethod.getMethodAnnotation(ExecutedMethodLog.class);
            if (methodAnnotation == null) {
                return true;
            }
            if (methodAnnotation.time()) {
                request.setAttribute("startTime", System.currentTimeMillis());
            }
            if (methodAnnotation.params()) {
                System.out.println("params: " + request.getParameterMap());
            }
            if (methodAnnotation.result()) {
                System.out.println("result: " + response);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            ExecutedMethodLog methodAnnotation = handlerMethod.getMethodAnnotation(ExecutedMethodLog.class);
            if (methodAnnotation == null) {
                return;
            }
            if (methodAnnotation.time()) {
                long startTime = (long) request.getAttribute("startTime");
                System.out.println("executed time: " + (System.currentTimeMillis() - startTime));
            }
        }
    }
}
